package it.sd.pwframework.business.service.impl;

import it.sd.pwframework.business.service.BatchService;
import it.sd.pwframework.business.service.crud.MediaTypeService;
import it.sd.pwframework.business.service.crud.RemoteSourceService;
import it.sd.pwframework.persistence.model.MediaType;
import it.sd.pwframework.persistence.model.RemoteSource;

import java.util.HashMap;
import java.util.List;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("batchService")
public class BatchServiceImpl implements BatchService {

    protected Logger log = org.slf4j.LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MediaTypeService mediaTypeService;
    
    @Autowired
    private RemoteSourceService remoteSourceService;
    
    @Transactional
	public void initDb() throws Exception {

    	createMediaType("FILM", "Film");
    	createMediaType("BOOK", "Libro");
    	createMediaType("COMIC", "Fumetto");
    	
    	createRemoteSource("IMDB", "Internet Movie Database", "http://www.imdb.com${key}");
		
	}
    
    private void createMediaType(String codice, String descrizione) {
    	
    	MediaType mt = mediaTypeService.getByCode(codice);
    	if (mt==null) {
    		mt = new MediaType();
    		mt.setCodice(codice);
    		mt.setDescription(descrizione);
    		mediaTypeService.saveOrUpdate(mt);
    	}
    	
    }

    private void createRemoteSource(String codice, String descrizione, String url) {
    	
    	RemoteSource rs = remoteSourceService.getByCode(codice);
    	if (rs==null) {
    		rs = new RemoteSource();
    		rs.setCodice(codice);
    		rs.setDescription(descrizione);
    		rs.setUrl(url);
    		remoteSourceService.saveOrUpdate(rs);
    	}
    	
    }

}
